﻿using Infrastructure.DbUtility;
using Infrastructure.Utility;
using System;
using System.Data;
using System.IO;
using System.Security.Cryptography;
using System.Web;

/// <summary>
/// UploadHelper 的摘要说明
/// </summary>
public class UploadHelper
{
    static readonly SHA1CryptoServiceProvider osha1 = new SHA1CryptoServiceProvider();
    public UploadHelper()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    public DataRow Upload(HttpPostedFile file, bool isCreateThumbnail)
    {
        var stream = file.InputStream;
        var fileRow = this.CheckUploadFile(stream);
        var fileId = fileRow.Value("fileid");
        if (isCreateThumbnail)
        {
            if (fileRow.Value("flag") != "T") return CreateThumbnail(this.SaveFile(file, fileId, fileRow.Value("sha1")));
            else return GetThumbnail(fileRow);
        }
        else
        {
            if (fileRow.Value("flag") != "T") return this.SaveFile(file, fileId, fileRow.Value("sha1"));
            else return fileRow;
        }
    }

    private DataRow GetThumbnail(DataRow fileRow)
    {
        var table = fileRow.Table;
        if (!table.Columns.Contains("thumbnail")) table.Columns.Add("thumbnail");
        //fileRow["thumbnail"] = HttpContext.Current.Server.MapPath("~/thumbnail/" + fileRow.Value("fileid") + ".jpg");
        fileRow["thumbnail"] = "/content/images/video-128.png";
        return fileRow;
    }

    private DataRow CreateThumbnail(DataRow dataRow)
    {
        var fullpath = dataRow.Value("fullPath");

        var table = dataRow.Table;
        if (!table.Columns.Contains("thumbnail")) table.Columns.Add("thumbnail");
        //todo : 生成缩略图。
        dataRow["thumbnail"] = "/content/images/video-128.png";
        return dataRow;
    }

    public DataRow CheckUploadFile(Stream stream)
    {
        DataRow fileRow = null;
        byte[] arrHash = osha1.ComputeHash(stream); //计算指定Stream 对象的哈希值
        //由以连字符分隔的十六进制对构成的String，其中每一对表示value 中对应的元素；例如“F-2C-4A”
        var sha1 = System.BitConverter.ToString(arrHash).Replace("-", string.Empty);
        var dataTable = new DataTable();
        DbHelper helper = new DbHelper();
        dataTable = helper.ExecQueryEx("EXEC usp_com_getfileid {0}", sha1);

        if (dataTable == null || dataTable.Rows.Count == 0) throw new Exception("无法获取文件ID,上传失败。");
        else fileRow = dataTable.Rows[0];

        if (fileRow.Value("flag") == "F") fileRow["sha1"] = sha1;
        return fileRow;
    }

    private DataRow SaveFile(HttpPostedFile httpPostedFile, string fileId, string sha1)
    {
        string name = Path.GetFileName(httpPostedFile.FileName);
        string fullPath = this.GetSavePath(fileId, name);
        httpPostedFile.SaveAs(fullPath);
        var table = PushToDb(fileId, name, Path.GetExtension(name), fullPath, sha1);
        return table == null || table.Rows.Count == 0 ? null : table.Rows[0];
    }

    private DataTable PushToDb(string fileId, string name, string extension, string fullPath, string sha1)
    {
        DbHelper db = new DbHelper();
        return db.ExecQueryEx("INSERT INTO Attachment ([aid],[name],[type],[fullPath],[sha1]) VALUES ({0},{1},{2},{3},{4}) SELECT 'F' [flag],[aid] fileid,* FROM Attachment (NOLOCK) WHERE aid = {0}", fileId, name, extension, fullPath, sha1);
    }


    public string GetSizeText(long size)
    {
        string[] arr = new string[] { "B", "KB", "MB", "GB", "TB", "PB" };
        int index = 0;
        double val = size;
        while (true)
        {
            if ((size = size / 1024) == 0) break;
            val = Math.Round(size * 1.0 / 1024, 2);
            index++;
        }
        return val + arr[index];
    }
    private string GetSavePath(string fileid, string fileName)
    {
        var path = HttpContext.Current.Server.MapPath(string.Concat("~/attchment/", fileid, Path.GetExtension(fileName)));
        var dir = Path.GetDirectoryName(path);
        if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
        return path;
    }
}